<?php

namespace App\Classes\Image;

use Image;

Class UploadImage
{
	/**
	 * [图片上传 description]
	 * @return [type] [description]
	 */
	public static function uploadImage($image, $rootDir, $allowedExtensions, $maxSize, $resize)
	{
        if ($image) {
            if ($image->isValid()) {
            	// 判断图片格式是否符合
                if (!$allowedExtensions) {
                    $allowedExtensions = ["png","jpg","gif","jpeg"];
                }
                if ($image->getClientOriginalExtension() && !in_array($image->getClientOriginalExtension(), $allowedExtensions)) {
                    return ['error' => 'You may only upload png, jpg, jpeg or gif.'];
                }
                // 判断图片是否超过大小限制
                $size = $image->getSize();
                if (!$maxSize) {
                	$maxSize = config('custom.base.img_max_size');
                }
            	if ($size > $maxSize) {
            		return ['error' => 'The size of the picture is beyond the maximum limit'];
            	}
                // 临时文件的绝对路径
                $realPath = $image->getRealPath();
                if ($resize['width'] && $resize['height']){
                    $img = Image::make($realPath)->resize($resize['width'], $resize['height']);
                } else {
                    $img = Image::make($realPath);
                }
                // 获得图片的扩展名
                $extension = $image->getClientOriginalExtension();
                // 重新命名上传文件名字
                $newImageName = md5(time()) . random_int(1000, 9999) . "." . $extension;
                // 图片上传路径
                if (!$rootDir) {
                	$rootDir = config('filesystems.disks.admin.root');
                }
                // 图片的完整路径
                $fullPath = $rootDir . '/' . $newImageName;
                $bool = $img->save($fullPath);
        		return $newImageName;
            }
        }
	}
}

